-- PurchaseToolkit
-- Created by lijh Sep/23/2016
-- 内购工具类，主要提供以下功能：
-- 1. 通过 web 获取商品列表信息
-- 2. 进行商品的预充值，得到订单编号等信息

module("PurchaseToolkit", package.seeall);

local PURE_FILE = "PurchaseToolkit";

local CHARGE_ERR_NETWORK = 1000;   -- 网络错误

local productsInfo = {};

-- 重试获取商品信息时间间隔
local retryInterval = 5;

-- 获取商品列表信息
function fetchProductsInfo(productsInfoUrl, onSuccess)
    local function whenResponse(responseData)

        trace(PURE_FILE, "fetch products info with response:" .. tostring(responseData));

        if not responseData then
            -- 获取商品信息失败，设置定时器重试
            ScheduleM.createScheme("PurchaseToolkit", function()
                fetchProductsInfo(productsInfoUrl, onSuccess);
            end, retryInterval, false);

            return;
        end

        local ret = string.parseJsonToTable(responseData);
        local purchases = ret["purchases"];
        if not purchases then
            return;
        end

        for i = 1, #purchases do
            local productInfo = purchases[i];
            local sku = productInfo["sku"];
            productsInfo[sku] = productInfo;
        end

        onSuccess(productsInfo);
    end

    -- 到远程主机获取数据
    getRemoteHostData(productsInfoUrl, whenResponse, true);
end

-- 预充值
function prePurchase(sku, prePurchaseUrl, platform, payChannel, onPrechargeOk, onPrechargeFail)
    local function whenResponse(responseData)
        trace(PURE_FILE, "pre-purchase with response:" .. tostring(responseData));

        if not responseData then
            onPrechargeFail();

            doAlert(string.format(getLocStr("charge_failed"), CHARGE_ERR_NETWORK));
            return;
        end

        local ret = string.parseJsonToTable(responseData);
        if ret["error"] == 0 then
            -- 成功
            local orderId = ret["preOrder"];

            if orderId then
                onPrechargeOk(orderId);
            end
        else
            -- 失败
            onPrechargeFail();

            doAlert(string.format(getLocStr("charge_failed"), ret["error"]));
        end
    end

    -- 发送 post 数据
    local serverId   = tostring(getCurrentServerId());
    local account    = getGaming3rdAccount();
    local role       = ME.user.dbase:query("rid");
    local order      = genOrderId();
    local price      = tostring(getProductPrice(sku));
    local type       = getProductType(sku);
    local amount     = tostring(1);
    local postData = string.format("sku=%s&platform=%s&server=%s&account=%s&role=%s&order=%s&price=%s&type=%s&amount=%s&payChannel=%s",
        sku, platform, serverId, account, role, order, price, type, amount, payChannel);

    postDataToRemoteHost(prePurchaseUrl, postData, whenResponse);
end

-- 获取某个商品的价格
function getProductPrice(sku)
    local productInfo = productsInfo[sku];
    if not productInfo then
        return 0;
    end

    return productInfo["price"];
end

-- 获取某个商品类型
function getProductType(sku)
    local productInfo = productsInfo[sku];
    if not productInfo then
        return "";
    end

    return tostring(productInfo["type"]);
end

-- 获取商品信息
function findPurchase(sku)
    return productsInfo[sku];
end

-- 生成 orderId
-- iOS 平台下这个 orderId 没有什么实际的用处，因为预充值表中使用的 key 是主键 precharge_id，充值表使用的 key 是苹果订单号
-- 这里先兼容之前 OC 中的写法，暂时保留 orderId
function genOrderId()
    local uuid = "";

    if isIosPlatform() then
        uuid = callOCFuncWithClass("QCToolkit", "UUID");
        uuid = string.gsub(uuid, "-", "");
    elseif isAndroidPlatform() then
        uuid = callJavaFunc("UUID", {}, "()Ljava/lang/String;");
        uuid = string.gsub(uuid, "-", "");
    end

    local orderId = string.format("%d_%s", getCurrentServerId(), uuid);
    return orderId;
end
